import request from '@/utils/request'

export default function exportExcel(params, url) {
  request({
    url: url,
    method: 'get',
    params,
    responseType: 'blob'
  }).then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
    const href = window.URL.createObjectURL(blob) // 创建下载的链接
    const downloadElement = document.createElement('a')
    downloadElement.href = href
    downloadElement.download = decodeURI(res.headers['filename']) // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  }).catch(() => {
    return {
      message: '下载失败！',
      type: 'error',
      showClose: true
    }
  })
}

export function exportExcelPost(data, url) {
  request({
    url: url,
    method: 'POST',
    data,
    responseType: 'blob'
  }).then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
    const href = window.URL.createObjectURL(blob) // 创建下载的链接
    const downloadElement = document.createElement('a')
    downloadElement.href = href
    downloadElement.download = decodeURI(res.headers['filename']) // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  }).catch(() => {
    return {
      message: '下载失败！',
      type: 'error',
      showClose: true
    }
  })
}
